#include "dtu_network.h"
#include "dtu_log.h"
#include "dtu_memory.h"
#include "dtu_config.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>

/* 全局网络管理器 */
static network_manager_t g_network_manager = {0};

/* 网络事件回调 */
static network_event_callback_t g_event_callback = NULL;
static void* g_event_user_data = NULL;

/* 内部函数声明 */
static void* network_monitor_thread(void* arg);
static dtu_error_t update_interface_info(network_type_t type);
static void notify_network_event(network_event_type_t event_type, network_type_t network_type, const char* message);
static dtu_error_t configure_ethernet_interface(const network_config_t* config);
static dtu_error_t configure_wifi_interface(const network_config_t* network_config, const wifi_config_t* wifi_config);
static dtu_error_t configure_lte_interface(const network_config_t* network_config, const lte_config_t* lte_config);
static void* lte_reconnect_thread(void* arg);

dtu_error_t dtu_network_init(dtu_model_t device_model)
{
    if (g_network_manager.initialized) {
        return DTU_OK;
    }

    memset(&g_network_manager, 0, sizeof(network_manager_t));

    /* 初始化互斥锁 */
    if (pthread_mutex_init(&g_network_manager.mutex, NULL) != 0) {
        return DTU_ERROR;
    }

    g_network_manager.device_model = device_model;
    g_network_manager.active_interface = -1;
    g_network_manager.monitor_interval = 5; /* 默认5秒监控间隔 */

    /* 初始化网络接口信息 */
    for (int i = 0; i < 3; i++) {
        g_network_manager.interfaces[i].type = (network_type_t)i;
        g_network_manager.interfaces[i].status = NETWORK_STATUS_DISCONNECTED;
        snprintf(g_network_manager.interfaces[i].interface_name, 
                sizeof(g_network_manager.interfaces[i].interface_name), 
                "if%d", i);
    }

    /* 根据设备型号设置可用接口 */
    switch (device_model) {
        case DTU_MODEL_ETHERNET_ONLY:
            /* 只有以太网接口可用 */
            break;
        case DTU_MODEL_WIFI_ETHERNET:
            /* WiFi和以太网接口可用 */
            break;
        case DTU_MODEL_4G_ETHERNET:
            /* 4G和以太网接口可用 */
            break;
        default:
            pthread_mutex_destroy(&g_network_manager.mutex);
            return DTU_ERROR_INVALID_PARAM;
    }

    g_network_manager.initialized = true;
    g_network_manager.running = true;

    /* 如果是4G版本，启动4G重拨线程 */
    if (device_model == DTU_MODEL_4G_ETHERNET) {
        pthread_t lte_thread;
        if (pthread_create(&lte_thread, NULL, lte_reconnect_thread, NULL) == 0) {
            pthread_detach(lte_thread);
            DTU_LOG_INFO("4G reconnect thread started");
        } else {
            DTU_LOG_ERROR("Failed to create 4G reconnect thread");
        }
    }

    DTU_LOG_INFO("Network manager initialized for device model %d", device_model);
    return DTU_OK;
}

void dtu_network_cleanup(void)
{
    if (!g_network_manager.initialized) {
        return;
    }

    /* 停止监控线程 */
    dtu_network_stop_monitor();

    pthread_mutex_lock(&g_network_manager.mutex);
    g_network_manager.initialized = false;
    g_network_manager.running = false; /* 停止4G重拨线程 */
    pthread_mutex_unlock(&g_network_manager.mutex);

    /* 等待4G重拨线程结束 */
    sleep(1);

    pthread_mutex_destroy(&g_network_manager.mutex);

    DTU_LOG_INFO("Network manager cleanup completed");
}

dtu_error_t dtu_network_start_monitor(void)
{
    if (!g_network_manager.initialized) {
        return DTU_ERROR;
    }

    pthread_mutex_lock(&g_network_manager.mutex);

    if (g_network_manager.monitor_running) {
        pthread_mutex_unlock(&g_network_manager.mutex);
        return DTU_OK;
    }

    g_network_manager.monitor_running = true;

    /* 创建监控线程 */
    if (pthread_create(&g_network_manager.monitor_thread, NULL, network_monitor_thread, NULL) != 0) {
        g_network_manager.monitor_running = false;
        pthread_mutex_unlock(&g_network_manager.mutex);
        return DTU_ERROR;
    }

    pthread_mutex_unlock(&g_network_manager.mutex);

    DTU_LOG_INFO("Network monitor started");
    return DTU_OK;
}

void dtu_network_stop_monitor(void)
{
    if (!g_network_manager.initialized || !g_network_manager.monitor_running) {
        return;
    }

    pthread_mutex_lock(&g_network_manager.mutex);
    g_network_manager.monitor_running = false;
    pthread_mutex_unlock(&g_network_manager.mutex);

    /* 等待监控线程结束 */
    pthread_join(g_network_manager.monitor_thread, NULL);

    DTU_LOG_INFO("Network monitor stopped");
}

dtu_error_t dtu_network_config_ethernet(const network_config_t* config)
{
    if (!g_network_manager.initialized || !config) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_network_manager.mutex);
    dtu_error_t ret = configure_ethernet_interface(config);
    pthread_mutex_unlock(&g_network_manager.mutex);

    if (ret == DTU_OK) {
        DTU_LOG_INFO("Ethernet interface configured successfully");
        notify_network_event(NETWORK_EVENT_IP_CHANGED, NETWORK_TYPE_ETHERNET, "Ethernet configured");
    } else {
        DTU_LOG_ERROR("Failed to configure ethernet interface");
    }

    return ret;
}

dtu_error_t dtu_network_config_wifi(const network_config_t* network_config,
                                    const wifi_config_t* wifi_config)
{
    if (!g_network_manager.initialized || !network_config || !wifi_config) {
        return DTU_ERROR_INVALID_PARAM;
    }

    if (g_network_manager.device_model == DTU_MODEL_ETHERNET_ONLY) {
        return DTU_ERROR_NOT_SUPPORTED;
    }

    pthread_mutex_lock(&g_network_manager.mutex);
    dtu_error_t ret = configure_wifi_interface(network_config, wifi_config);
    pthread_mutex_unlock(&g_network_manager.mutex);

    if (ret == DTU_OK) {
        DTU_LOG_INFO("WiFi interface configured successfully");
        notify_network_event(NETWORK_EVENT_IP_CHANGED, NETWORK_TYPE_WIFI, "WiFi configured");
    } else {
        DTU_LOG_ERROR("Failed to configure WiFi interface");
    }

    return ret;
}

dtu_error_t dtu_network_config_lte(const network_config_t* network_config,
                                   const lte_config_t* lte_config)
{
    if (!g_network_manager.initialized || !network_config || !lte_config) {
        return DTU_ERROR_INVALID_PARAM;
    }

    if (g_network_manager.device_model != DTU_MODEL_4G_ETHERNET) {
        return DTU_ERROR_NOT_SUPPORTED;
    }

    pthread_mutex_lock(&g_network_manager.mutex);
    dtu_error_t ret = configure_lte_interface(network_config, lte_config);
    pthread_mutex_unlock(&g_network_manager.mutex);

    if (ret == DTU_OK) {
        DTU_LOG_INFO("4G interface configured successfully");
        notify_network_event(NETWORK_EVENT_IP_CHANGED, NETWORK_TYPE_4G, "4G configured");
    } else {
        DTU_LOG_ERROR("Failed to configure 4G interface");
    }

    return ret;
}

dtu_error_t dtu_network_connect(network_type_t type)
{
    if (!g_network_manager.initialized || type < 0 || type >= 3) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_network_manager.mutex);

    network_interface_t* interface = &g_network_manager.interfaces[type];
    
    if (interface->status == NETWORK_STATUS_CONNECTED) {
        pthread_mutex_unlock(&g_network_manager.mutex);
        return DTU_OK;
    }

    interface->status = NETWORK_STATUS_CONNECTING;
    interface->connect_time = time(NULL);

    /* TODO: 实现具体的连接逻辑 */
    /* 这里应该根据网络类型执行相应的连接操作 */
    
    /* 模拟连接成功 */
    interface->status = NETWORK_STATUS_CONNECTED;
    interface->last_activity = time(NULL);

    pthread_mutex_unlock(&g_network_manager.mutex);

    DTU_LOG_INFO("Network interface %s connected", dtu_network_type_string(type));
    notify_network_event(NETWORK_EVENT_CONNECTED, type, "Interface connected");

    return DTU_OK;
}

dtu_error_t dtu_network_disconnect(network_type_t type)
{
    if (!g_network_manager.initialized || type < 0 || type >= 3) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_network_manager.mutex);

    network_interface_t* interface = &g_network_manager.interfaces[type];
    
    if (interface->status == NETWORK_STATUS_DISCONNECTED) {
        pthread_mutex_unlock(&g_network_manager.mutex);
        return DTU_OK;
    }

    interface->status = NETWORK_STATUS_DISCONNECTED;
    interface->ip_address[0] = '\0';
    interface->connect_time = 0;

    /* 如果这是当前活动接口，需要切换到其他接口 */
    if (g_network_manager.active_interface == (int)type) {
        g_network_manager.active_interface = -1;

        /* 尝试找到其他可用接口 */
        for (int i = 0; i < 3; i++) {
            if (i != (int)type && g_network_manager.interfaces[i].status == NETWORK_STATUS_CONNECTED) {
                g_network_manager.active_interface = i;
                break;
            }
        }
    }

    pthread_mutex_unlock(&g_network_manager.mutex);

    DTU_LOG_INFO("Network interface %s disconnected", dtu_network_type_string(type));
    notify_network_event(NETWORK_EVENT_DISCONNECTED, type, "Interface disconnected");

    return DTU_OK;
}

network_status_t dtu_network_check_status(network_type_t type)
{
    if (!g_network_manager.initialized || type < 0 || type >= 3) {
        return NETWORK_STATUS_ERROR;
    }

    pthread_mutex_lock(&g_network_manager.mutex);
    network_status_t status = g_network_manager.interfaces[type].status;
    pthread_mutex_unlock(&g_network_manager.mutex);

    return status;
}

dtu_error_t dtu_network_get_interface(network_type_t type, network_interface_t* interface)
{
    if (!g_network_manager.initialized || type < 0 || type >= 3 || !interface) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_network_manager.mutex);
    *interface = g_network_manager.interfaces[type];
    pthread_mutex_unlock(&g_network_manager.mutex);

    return DTU_OK;
}

network_type_t dtu_network_get_active_interface(void)
{
    if (!g_network_manager.initialized) {
        return -1;
    }

    pthread_mutex_lock(&g_network_manager.mutex);
    int active = g_network_manager.active_interface;
    pthread_mutex_unlock(&g_network_manager.mutex);

    return active;
}

dtu_error_t dtu_network_set_active_interface(network_type_t type)
{
    if (!g_network_manager.initialized || type < 0 || type >= 3) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_network_manager.mutex);

    if (g_network_manager.interfaces[type].status != NETWORK_STATUS_CONNECTED) {
        pthread_mutex_unlock(&g_network_manager.mutex);
        return DTU_ERROR_NETWORK;
    }

    g_network_manager.active_interface = type;

    pthread_mutex_unlock(&g_network_manager.mutex);

    DTU_LOG_INFO("Active network interface set to %s", dtu_network_type_string(type));
    return DTU_OK;
}

dtu_error_t dtu_network_register_event_callback(network_event_callback_t callback, void* user_data)
{
    if (!callback) {
        return DTU_ERROR_INVALID_PARAM;
    }

    g_event_callback = callback;
    g_event_user_data = user_data;

    DTU_LOG_DEBUG("Network event callback registered");
    return DTU_OK;
}

dtu_error_t dtu_network_unregister_event_callback(void)
{
    g_event_callback = NULL;
    g_event_user_data = NULL;

    DTU_LOG_DEBUG("Network event callback unregistered");
    return DTU_OK;
}

/* 内部函数实现 */
static void* network_monitor_thread(void* arg)
{
    (void)arg;

    DTU_LOG_INFO("Network monitor thread started");

    while (g_network_manager.monitor_running) {
        /* 更新所有网络接口信息 */
        for (int i = 0; i < 3; i++) {
            update_interface_info((network_type_t)i);
        }

        /* 检查是否需要自动切换活动接口 */
        pthread_mutex_lock(&g_network_manager.mutex);
        
        if (g_network_manager.active_interface >= 0) {
            network_interface_t* active = &g_network_manager.interfaces[g_network_manager.active_interface];
            if (active->status != NETWORK_STATUS_CONNECTED) {
                /* 当前活动接口断开，尝试切换到其他接口 */
                g_network_manager.active_interface = -1;
                
                for (int i = 0; i < 3; i++) {
                    if (g_network_manager.interfaces[i].status == NETWORK_STATUS_CONNECTED) {
                        g_network_manager.active_interface = i;
                        DTU_LOG_INFO("Auto-switched to network interface %s", dtu_network_type_string(i));
                        break;
                    }
                }
            }
        } else {
            /* 没有活动接口，尝试找到可用接口 */
            for (int i = 0; i < 3; i++) {
                if (g_network_manager.interfaces[i].status == NETWORK_STATUS_CONNECTED) {
                    g_network_manager.active_interface = i;
                    DTU_LOG_INFO("Auto-selected network interface %s", dtu_network_type_string(i));
                    break;
                }
            }
        }

        pthread_mutex_unlock(&g_network_manager.mutex);

        /* 休眠监控间隔时间 */
        sleep(g_network_manager.monitor_interval);
    }

    DTU_LOG_INFO("Network monitor thread stopped");
    return NULL;
}

static dtu_error_t update_interface_info(network_type_t type)
{
    /* TODO: 实现真实的网络接口信息更新 */
    /* 这里应该通过系统调用获取实际的网络接口状态 */
    
    pthread_mutex_lock(&g_network_manager.mutex);
    
    network_interface_t* interface = &g_network_manager.interfaces[type];
    
    /* 模拟网络状态检查 */
    switch (type) {
        case NETWORK_TYPE_ETHERNET:
            /* 检查以太网接口状态 */
            break;
        case NETWORK_TYPE_WIFI:
            /* 检查WiFi接口状态 */
            break;
        case NETWORK_TYPE_4G:
            /* 检查4G接口状态 */
            break;
    }
    
    interface->last_activity = time(NULL);
    
    pthread_mutex_unlock(&g_network_manager.mutex);
    
    return DTU_OK;
}

static void notify_network_event(network_event_type_t event_type, network_type_t network_type, const char* message)
{
    if (!g_event_callback) {
        return;
    }

    network_event_t event;
    event.type = event_type;
    event.network_type = network_type;
    event.timestamp = time(NULL);
    DTU_STRNCPY(event.message, message ? message : "", sizeof(event.message));

    g_event_callback(&event, g_event_user_data);
}

static dtu_error_t configure_ethernet_interface(const network_config_t* config)
{
    if (!config) {
        return DTU_ERROR_INVALID_PARAM;
    }

    DTU_LOG_INFO("Configuring ethernet interface");
    DTU_LOG_INFO("DHCP: %s", config->dhcp_enable ? "enabled" : "disabled");

    /* 获取以太网接口 */
    network_interface_t* eth_interface = &g_network_manager.interfaces[NETWORK_TYPE_ETHERNET];
    const char* eth_interface_name = "eth0"; /* 默认以太网接口名 */

    /* 先停止现有的网络配置 */
    char cmd[256];
    snprintf(cmd, sizeof(cmd), "ifconfig %s down", eth_interface_name);
    system(cmd);

    /* 杀死可能存在的dhclient进程 */
    snprintf(cmd, sizeof(cmd), "killall dhclient 2>/dev/null || true");
    system(cmd);

    /* 启动网络接口 */
    snprintf(cmd, sizeof(cmd), "ifconfig %s up", eth_interface_name);
    if (system(cmd) != 0) {
        DTU_LOG_ERROR("Failed to bring up ethernet interface %s", eth_interface_name);
        eth_interface->status = NETWORK_STATUS_ERROR;
        return DTU_ERROR;
    }

    if (config->dhcp_enable) {
        /* 启用DHCP */
        DTU_LOG_INFO("Starting DHCP client for ethernet interface");

        /* 启动DHCP客户端 */
        snprintf(cmd, sizeof(cmd), "dhclient -v %s &", eth_interface_name);
        if (system(cmd) != 0) {
            DTU_LOG_ERROR("Failed to start DHCP client");
            eth_interface->status = NETWORK_STATUS_ERROR;
            return DTU_ERROR;
        }

        /* 等待DHCP获取IP地址 */
        int retry_count = 0;
        const int max_retries = 30; /* 最多等待30秒 */

        while (retry_count < max_retries) {
            sleep(1);

            /* 检查是否获取到IP地址 */
            FILE* fp = popen("ifconfig eth0 | grep 'inet ' | awk '{print $2}'", "r");
            if (fp) {
                char ip_str[32] = {0};
                if (fgets(ip_str, sizeof(ip_str), fp) && strlen(ip_str) > 7) {
                    /* 去除换行符 */
                    ip_str[strcspn(ip_str, "\n")] = 0;
                    DTU_STRNCPY(eth_interface->ip_address, ip_str, sizeof(eth_interface->ip_address));

                    /* 获取网关信息 */
                    pclose(fp);
                    fp = popen("route -n | grep '^0.0.0.0' | awk '{print $2}' | head -1", "r");
                    if (fp) {
                        char gw_str[32] = {0};
                        if (fgets(gw_str, sizeof(gw_str), fp)) {
                            gw_str[strcspn(gw_str, "\n")] = 0;
                            DTU_STRNCPY(eth_interface->gateway, gw_str, sizeof(eth_interface->gateway));
                        }
                        pclose(fp);
                    }

                    /* 获取子网掩码 */
                    fp = popen("ifconfig eth0 | grep 'netmask' | awk '{print $4}'", "r");
                    if (fp) {
                        char mask_str[32] = {0};
                        if (fgets(mask_str, sizeof(mask_str), fp)) {
                            mask_str[strcspn(mask_str, "\n")] = 0;
                            DTU_STRNCPY(eth_interface->netmask, mask_str, sizeof(eth_interface->netmask));
                        }
                        pclose(fp);
                    }

                    eth_interface->status = NETWORK_STATUS_CONNECTED;
                    DTU_LOG_INFO("DHCP configuration completed, IP: %s", eth_interface->ip_address);
                    break;
                }
                pclose(fp);
            }

            retry_count++;
        }

        if (retry_count >= max_retries) {
            DTU_LOG_ERROR("DHCP timeout, failed to get IP address");
            eth_interface->status = NETWORK_STATUS_ERROR;
            return DTU_ERROR;
        }

    } else {
        /* 静态IP配置 */
        DTU_LOG_INFO("Configuring static IP for ethernet interface");
        DTU_LOG_INFO("IP: %s, Netmask: %s, Gateway: %s", config->ip, config->netmask, config->gateway);

        /* 验证IP地址格式 */
        if (strlen(config->ip) == 0 || strlen(config->netmask) == 0 || strlen(config->gateway) == 0) {
            DTU_LOG_ERROR("Invalid static IP configuration");
            return DTU_ERROR_INVALID_PARAM;
        }

        /* 设置静态IP地址和子网掩码 */
        snprintf(cmd, sizeof(cmd), "ifconfig %s %s netmask %s",
                 eth_interface_name, config->ip, config->netmask);
        if (system(cmd) != 0) {
            DTU_LOG_ERROR("Failed to set static IP address");
            eth_interface->status = NETWORK_STATUS_ERROR;
            return DTU_ERROR;
        }

        /* 删除默认路由 */
        system("route del default 2>/dev/null || true");

        /* 添加默认网关 */
        snprintf(cmd, sizeof(cmd), "route add default gw %s", config->gateway);
        if (system(cmd) != 0) {
            DTU_LOG_ERROR("Failed to set default gateway");
            eth_interface->status = NETWORK_STATUS_ERROR;
            return DTU_ERROR;
        }

        /* 设置DNS服务器 */
        FILE* resolv_fp = fopen("/etc/resolv.conf", "w");
        if (resolv_fp) {
            if (strlen(config->dns1) > 0) {
                fprintf(resolv_fp, "nameserver %s\n", config->dns1);
            }
            if (strlen(config->dns2) > 0) {
                fprintf(resolv_fp, "nameserver %s\n", config->dns2);
            }
            fclose(resolv_fp);
        }

        /* 更新接口信息 */
        DTU_STRNCPY(eth_interface->ip_address, config->ip, sizeof(eth_interface->ip_address));
        DTU_STRNCPY(eth_interface->netmask, config->netmask, sizeof(eth_interface->netmask));
        DTU_STRNCPY(eth_interface->gateway, config->gateway, sizeof(eth_interface->gateway));
        DTU_STRNCPY(eth_interface->dns1, config->dns1, sizeof(eth_interface->dns1));
        DTU_STRNCPY(eth_interface->dns2, config->dns2, sizeof(eth_interface->dns2));

        eth_interface->status = NETWORK_STATUS_CONNECTED;
        DTU_LOG_INFO("Static IP configuration completed");
    }

    eth_interface->connect_time = time(NULL);
    eth_interface->last_activity = time(NULL);

    /* 设置以太网为活动接口 */
    g_network_manager.active_interface = NETWORK_TYPE_ETHERNET;

    return DTU_OK;
}

static dtu_error_t configure_wifi_interface(const network_config_t* network_config, const wifi_config_t* wifi_config)
{
    if (!network_config || !wifi_config) {
        return DTU_ERROR_INVALID_PARAM;
    }

    DTU_LOG_INFO("Configuring WiFi interface");
    DTU_LOG_INFO("SSID: %s", wifi_config->ssid);
    DTU_LOG_INFO("Security Type: %d", wifi_config->security_type);

    /* 获取WiFi接口 */
    network_interface_t* wifi_interface = &g_network_manager.interfaces[NETWORK_TYPE_WIFI];
    const char* wifi_interface_name = "wlan0"; /* 默认WiFi接口名 */

    /* 验证WiFi配置 */
    if (strlen(wifi_config->ssid) == 0) {
        DTU_LOG_ERROR("WiFi SSID cannot be empty");
        return DTU_ERROR_INVALID_PARAM;
    }

    /* 设置WiFi接口状态为连接中 */
    wifi_interface->status = NETWORK_STATUS_CONNECTING;

    /* 停止现有的WiFi连接 */
    system("killall wpa_supplicant 2>/dev/null || true");
    system("killall dhclient 2>/dev/null || true");

    char cmd[512];
    snprintf(cmd, sizeof(cmd), "ifconfig %s down", wifi_interface_name);
    system(cmd);

    /* 启动WiFi接口 */
    snprintf(cmd, sizeof(cmd), "ifconfig %s up", wifi_interface_name);
    if (system(cmd) != 0) {
        DTU_LOG_ERROR("Failed to bring up WiFi interface %s", wifi_interface_name);
        wifi_interface->status = NETWORK_STATUS_ERROR;
        return DTU_ERROR;
    }

    /* 创建wpa_supplicant配置文件 */
    FILE* wpa_conf = fopen("/tmp/wpa_supplicant.conf", "w");
    if (!wpa_conf) {
        DTU_LOG_ERROR("Failed to create wpa_supplicant configuration file");
        wifi_interface->status = NETWORK_STATUS_ERROR;
        return DTU_ERROR;
    }

    fprintf(wpa_conf, "ctrl_interface=/var/run/wpa_supplicant\n");
    fprintf(wpa_conf, "update_config=1\n");
    fprintf(wpa_conf, "country=CN\n\n");
    fprintf(wpa_conf, "network={\n");
    fprintf(wpa_conf, "    ssid=\"%s\"\n", wifi_config->ssid);

    /* 根据安全类型设置认证方式 */
    switch (wifi_config->security_type) {
        case 0: /* 开放网络 */
            fprintf(wpa_conf, "    key_mgmt=NONE\n");
            break;
        case 1: /* WEP */
            fprintf(wpa_conf, "    key_mgmt=NONE\n");
            fprintf(wpa_conf, "    wep_key0=\"%s\"\n", wifi_config->password);
            break;
        case 2: /* WPA/WPA2 */
        default:
            fprintf(wpa_conf, "    psk=\"%s\"\n", wifi_config->password);
            break;
        case 3: /* WPA3 */
            fprintf(wpa_conf, "    key_mgmt=SAE\n");
            fprintf(wpa_conf, "    psk=\"%s\"\n", wifi_config->password);
            break;
    }

    fprintf(wpa_conf, "}\n");
    fclose(wpa_conf);

    /* 启动wpa_supplicant */
    snprintf(cmd, sizeof(cmd), "wpa_supplicant -B -i %s -c /tmp/wpa_supplicant.conf -D nl80211,wext",
             wifi_interface_name);
    if (system(cmd) != 0) {
        DTU_LOG_ERROR("Failed to start wpa_supplicant");
        wifi_interface->status = NETWORK_STATUS_ERROR;
        return DTU_ERROR;
    }

    /* 等待WiFi连接 */
    int retry_count = 0;
    const int max_retries = 30; /* 最多等待30秒 */
    bool connected = false;

    while (retry_count < max_retries && !connected) {
        sleep(1);

        /* 检查WiFi连接状态 */
        FILE* fp = popen("wpa_cli -i wlan0 status | grep wpa_state", "r");
        if (fp) {
            char status_line[128] = {0};
            if (fgets(status_line, sizeof(status_line), fp)) {
                if (strstr(status_line, "COMPLETED")) {
                    connected = true;
                    DTU_LOG_INFO("WiFi connected successfully");
                }
            }
            pclose(fp);
        }

        retry_count++;
    }

    if (!connected) {
        DTU_LOG_ERROR("WiFi connection timeout");
        wifi_interface->status = NETWORK_STATUS_ERROR;
        system("killall wpa_supplicant 2>/dev/null || true");
        return DTU_ERROR;
    }

    /* 配置IP地址 */
    if (network_config->dhcp_enable) {
        /* WiFi使用DHCP */
        DTU_LOG_INFO("Starting DHCP client for WiFi interface");

        snprintf(cmd, sizeof(cmd), "dhclient -v %s &", wifi_interface_name);
        if (system(cmd) != 0) {
            DTU_LOG_ERROR("Failed to start DHCP client for WiFi");
            wifi_interface->status = NETWORK_STATUS_ERROR;
            return DTU_ERROR;
        }

        /* 等待DHCP获取IP地址 */
        retry_count = 0;
        while (retry_count < 20) { /* 最多等待20秒 */
            sleep(1);

            /* 检查是否获取到IP地址 */
            snprintf(cmd, sizeof(cmd), "ifconfig %s | grep 'inet ' | awk '{print $2}'", wifi_interface_name);
            FILE* fp = popen(cmd, "r");
            if (fp) {
                char ip_str[32] = {0};
                if (fgets(ip_str, sizeof(ip_str), fp) && strlen(ip_str) > 7) {
                    ip_str[strcspn(ip_str, "\n")] = 0;
                    DTU_STRNCPY(wifi_interface->ip_address, ip_str, sizeof(wifi_interface->ip_address));
                    DTU_LOG_INFO("WiFi DHCP completed, IP: %s", wifi_interface->ip_address);
                    break;
                }
                pclose(fp);
            }
            retry_count++;
        }

    } else {
        /* WiFi使用静态IP */
        DTU_LOG_INFO("Configuring static IP for WiFi interface");

        snprintf(cmd, sizeof(cmd), "ifconfig %s %s netmask %s",
                 wifi_interface_name, network_config->ip, network_config->netmask);
        if (system(cmd) != 0) {
            DTU_LOG_ERROR("Failed to set static IP for WiFi");
            wifi_interface->status = NETWORK_STATUS_ERROR;
            return DTU_ERROR;
        }

        DTU_STRNCPY(wifi_interface->ip_address, network_config->ip, sizeof(wifi_interface->ip_address));
        DTU_STRNCPY(wifi_interface->netmask, network_config->netmask, sizeof(wifi_interface->netmask));
        DTU_STRNCPY(wifi_interface->gateway, network_config->gateway, sizeof(wifi_interface->gateway));
    }

    /* 获取WiFi信号强度 */
    FILE* fp = popen("iwconfig wlan0 | grep 'Signal level' | awk -F'=' '{print $3}' | awk '{print $1}'", "r");
    if (fp) {
        char signal_str[32] = {0};
        if (fgets(signal_str, sizeof(signal_str), fp)) {
            int signal_dbm = atoi(signal_str);
            /* 将dBm转换为百分比 (假设-30dBm为100%, -90dBm为0%) */
            wifi_interface->signal_strength = (signal_dbm + 90) * 100 / 60;
            if (wifi_interface->signal_strength > 100) wifi_interface->signal_strength = 100;
            if (wifi_interface->signal_strength < 0) wifi_interface->signal_strength = 0;
        }
        pclose(fp);
    }

    DTU_STRNCPY(wifi_interface->dns1, network_config->dns1, sizeof(wifi_interface->dns1));
    DTU_STRNCPY(wifi_interface->dns2, network_config->dns2, sizeof(wifi_interface->dns2));

    wifi_interface->status = NETWORK_STATUS_CONNECTED;
    wifi_interface->connect_time = time(NULL);
    wifi_interface->last_activity = time(NULL);

    /* 如果以太网未连接，设置WiFi为活动接口 */
    if (g_network_manager.interfaces[NETWORK_TYPE_ETHERNET].status != NETWORK_STATUS_CONNECTED) {
        g_network_manager.active_interface = NETWORK_TYPE_WIFI;
    }

    DTU_LOG_INFO("WiFi configuration completed successfully");
    return DTU_OK;
}

/* 4G模块AT命令发送函数 */
static dtu_error_t send_at_command(const char* command, char* response, size_t response_size, int timeout_sec)
{
    const char* modem_device = "/dev/ttyUSB2"; /* 4G模块AT命令端口 */

    /* 打开4G模块串口 */
    int fd = open(modem_device, O_RDWR | O_NOCTTY);
    if (fd < 0) {
        DTU_LOG_ERROR("Failed to open 4G modem device: %s", modem_device);
        return DTU_ERROR;
    }

    /* 配置串口参数 */
    struct termios tty;
    if (tcgetattr(fd, &tty) != 0) {
        close(fd);
        return DTU_ERROR;
    }

    cfsetospeed(&tty, B115200);
    cfsetispeed(&tty, B115200);
    tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;
    tty.c_iflag &= ~IGNBRK;
    tty.c_lflag = 0;
    tty.c_oflag = 0;
    tty.c_cc[VMIN] = 0;
    tty.c_cc[VTIME] = 5;
    tty.c_iflag &= ~(IXON | IXOFF | IXANY);
    tty.c_cflag |= (CLOCAL | CREAD);
    tty.c_cflag &= ~(PARENB | PARODD);
    tty.c_cflag &= ~CSTOPB;
    tty.c_cflag &= ~CRTSCTS;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        close(fd);
        return DTU_ERROR;
    }

    /* 发送AT命令 */
    char cmd_with_crlf[256];
    snprintf(cmd_with_crlf, sizeof(cmd_with_crlf), "%s\r\n", command);

    if (write(fd, cmd_with_crlf, strlen(cmd_with_crlf)) < 0) {
        close(fd);
        return DTU_ERROR;
    }

    /* 读取响应 */
    memset(response, 0, response_size);
    time_t start_time = time(NULL);
    size_t total_read = 0;

    while ((time(NULL) - start_time) < timeout_sec && total_read < (response_size - 1)) {
        char buffer[64];
        ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
        if (bytes_read > 0) {
            buffer[bytes_read] = '\0';
            strncat(response, buffer, response_size - total_read - 1);
            total_read += bytes_read;

            /* 检查是否收到完整响应 */
            if (strstr(response, "OK") || strstr(response, "ERROR")) {
                break;
            }
        }
        usleep(100000); /* 100ms */
    }

    close(fd);
    return (strlen(response) > 0) ? DTU_OK : DTU_ERROR;
}

static dtu_error_t configure_lte_interface(const network_config_t* network_config, const lte_config_t* lte_config)
{
    if (!network_config || !lte_config) {
        return DTU_ERROR_INVALID_PARAM;
    }

    DTU_LOG_INFO("Configuring 4G/LTE interface");
    DTU_LOG_INFO("APN: %s", lte_config->apn);
    DTU_LOG_INFO("Username: %s", lte_config->username);
    DTU_LOG_INFO("PIN Code: %d", lte_config->pin_code);

    /* 获取4G接口 */
    network_interface_t* lte_interface = &g_network_manager.interfaces[NETWORK_TYPE_4G];
    const char* ppp_interface = "ppp0"; /* PPP拨号接口 */

    /* 验证4G配置 */
    if (strlen(lte_config->apn) == 0) {
        DTU_LOG_ERROR("4G APN cannot be empty");
        return DTU_ERROR_INVALID_PARAM;
    }

    /* 设置4G接口状态为连接中 */
    lte_interface->status = NETWORK_STATUS_CONNECTING;

    char response[512];
    char command[256];

    /* 1. 检查4G模块状态 */
    DTU_LOG_INFO("Checking 4G modem status...");
    if (send_at_command("AT", response, sizeof(response), 3) != DTU_OK) {
        DTU_LOG_ERROR("4G modem not responding");
        lte_interface->status = NETWORK_STATUS_ERROR;
        return DTU_ERROR;
    }

    /* 2. 验证PIN码（如果需要） */
    if (lte_config->pin_code > 0) {
        DTU_LOG_INFO("Verifying PIN code: %d", lte_config->pin_code);

        /* 检查PIN状态 */
        if (send_at_command("AT+CPIN?", response, sizeof(response), 5) == DTU_OK) {
            if (strstr(response, "SIM PIN")) {
                /* 需要输入PIN码 */
                snprintf(command, sizeof(command), "AT+CPIN=%d", lte_config->pin_code);
                if (send_at_command(command, response, sizeof(response), 10) != DTU_OK ||
                    !strstr(response, "OK")) {
                    DTU_LOG_ERROR("PIN verification failed");
                    lte_interface->status = NETWORK_STATUS_ERROR;
                    return DTU_ERROR;
                }
                DTU_LOG_INFO("PIN verification successful");
            }
        }
    }

    /* 3. 等待网络注册 */
    DTU_LOG_INFO("Waiting for network registration...");
    int retry_count = 0;
    bool registered = false;

    while (retry_count < 30 && !registered) { /* 最多等待30秒 */
        if (send_at_command("AT+CREG?", response, sizeof(response), 3) == DTU_OK) {
            if (strstr(response, "+CREG: 0,1") || strstr(response, "+CREG: 0,5")) {
                registered = true;
                DTU_LOG_INFO("Network registration successful");
                break;
            }
        }
        sleep(1);
        retry_count++;
    }

    if (!registered) {
        DTU_LOG_ERROR("Network registration timeout");
        lte_interface->status = NETWORK_STATUS_ERROR;
        return DTU_ERROR;
    }

    /* 4. 设置APN */
    DTU_LOG_INFO("Setting APN: %s", lte_config->apn);
    snprintf(command, sizeof(command), "AT+CGDCONT=1,\"IP\",\"%s\"", lte_config->apn);
    if (send_at_command(command, response, sizeof(response), 5) != DTU_OK ||
        !strstr(response, "OK")) {
        DTU_LOG_ERROR("Failed to set APN");
        lte_interface->status = NETWORK_STATUS_ERROR;
        return DTU_ERROR;
    }

    /* 5. 设置认证信息（如果有） */
    if (strlen(lte_config->username) > 0 && strlen(lte_config->password) > 0) {
        DTU_LOG_INFO("Setting authentication: %s", lte_config->username);
        snprintf(command, sizeof(command), "AT+CGAUTH=1,1,\"%s\",\"%s\"",
                 lte_config->username, lte_config->password);
        send_at_command(command, response, sizeof(response), 5);
    }

    /* 6. 创建PPP拨号脚本 */
    FILE* chat_script = fopen("/tmp/4g-chat", "w");
    if (chat_script) {
        fprintf(chat_script, "ABORT 'BUSY'\n");
        fprintf(chat_script, "ABORT 'NO CARRIER'\n");
        fprintf(chat_script, "ABORT 'NO DIALTONE'\n");
        fprintf(chat_script, "ABORT 'ERROR'\n");
        fprintf(chat_script, "ABORT 'NO ANSWER'\n");
        fprintf(chat_script, "TIMEOUT 30\n");
        fprintf(chat_script, "'' 'ATZ'\n");
        fprintf(chat_script, "OK 'AT+CGDCONT=1,\"IP\",\"%s\"'\n", lte_config->apn);
        fprintf(chat_script, "OK 'ATD*99#'\n");
        fprintf(chat_script, "CONNECT ''\n");
        fclose(chat_script);
        chmod("/tmp/4g-chat", 0755);
    }

    /* 7. 启动PPP拨号 */
    DTU_LOG_INFO("Starting PPP dial-up...");

    /* 停止现有的PPP连接 */
    system("killall pppd 2>/dev/null || true");

    /* 启动PPP拨号 */
    char ppp_cmd[512];
    snprintf(ppp_cmd, sizeof(ppp_cmd),
             "pppd /dev/ttyUSB3 115200 connect 'chat -v -f /tmp/4g-chat' "
             "noauth defaultroute usepeerdns persist maxfail 0 &");

    if (system(ppp_cmd) != 0) {
        DTU_LOG_ERROR("Failed to start PPP dial-up");
        lte_interface->status = NETWORK_STATUS_ERROR;
        return DTU_ERROR;
    }

    /* 8. 等待PPP连接建立 */
    DTU_LOG_INFO("Waiting for PPP connection...");
    retry_count = 0;
    bool ppp_connected = false;

    while (retry_count < 60 && !ppp_connected) { /* 最多等待60秒 */
        /* 检查ppp0接口是否存在且有IP */
        FILE* fp = popen("ifconfig ppp0 2>/dev/null | grep 'inet ' | awk '{print $2}'", "r");
        if (fp) {
            char ip_str[32] = {0};
            if (fgets(ip_str, sizeof(ip_str), fp) && strlen(ip_str) > 7) {
                ip_str[strcspn(ip_str, "\n")] = 0;
                DTU_STRNCPY(lte_interface->ip_address, ip_str, sizeof(lte_interface->ip_address));
                ppp_connected = true;
                DTU_LOG_INFO("4G PPP connection established, IP: %s", lte_interface->ip_address);
            }
            pclose(fp);
        }

        if (!ppp_connected) {
            sleep(1);
            retry_count++;
        }
    }

    if (!ppp_connected) {
        DTU_LOG_ERROR("PPP connection timeout");
        lte_interface->status = NETWORK_STATUS_ERROR;
        system("killall pppd 2>/dev/null || true");
        return DTU_ERROR;
    }

    /* 9. 获取网络信息 */
    /* 获取网关信息 */
    FILE* fp = popen("route -n | grep ppp0 | grep '^0.0.0.0' | awk '{print $2}' | head -1", "r");
    if (fp) {
        char gw_str[32] = {0};
        if (fgets(gw_str, sizeof(gw_str), fp)) {
            gw_str[strcspn(gw_str, "\n")] = 0;
            DTU_STRNCPY(lte_interface->gateway, gw_str, sizeof(lte_interface->gateway));
        }
        pclose(fp);
    }

    /* 获取信号强度 */
    if (send_at_command("AT+CSQ", response, sizeof(response), 3) == DTU_OK) {
        char* csq_pos = strstr(response, "+CSQ: ");
        if (csq_pos) {
            int rssi = atoi(csq_pos + 6);
            if (rssi >= 0 && rssi <= 31) {
                /* 将RSSI转换为百分比 */
                lte_interface->signal_strength = (rssi * 100) / 31;
            }
        }
    }

    /* 设置DNS（通常由PPP自动获取） */
    DTU_STRNCPY(lte_interface->dns1, "8.8.8.8", sizeof(lte_interface->dns1));
    DTU_STRNCPY(lte_interface->dns2, "8.8.4.4", sizeof(lte_interface->dns2));

    lte_interface->status = NETWORK_STATUS_CONNECTED;
    lte_interface->connect_time = time(NULL);
    lte_interface->last_activity = time(NULL);

    /* 如果以太网未连接，设置4G为活动接口 */
    if (g_network_manager.interfaces[NETWORK_TYPE_ETHERNET].status != NETWORK_STATUS_CONNECTED) {
        g_network_manager.active_interface = NETWORK_TYPE_4G;
    }

    DTU_LOG_INFO("4G configuration completed successfully");
    return DTU_OK;
}

int dtu_network_get_all_interfaces(network_interface_t* interfaces, int count)
{
    if (!g_network_manager.initialized || !interfaces || count <= 0) {
        return 0;
    }

    pthread_mutex_lock(&g_network_manager.mutex);

    int copy_count = DTU_MIN(count, 3);
    for (int i = 0; i < copy_count; i++) {
        interfaces[i] = g_network_manager.interfaces[i];
    }

    pthread_mutex_unlock(&g_network_manager.mutex);
    return copy_count;
}

/* 4G断线重拨功能 */
static void* lte_reconnect_thread(void* arg)
{
    (void)arg;

    const dtu_config_t* config = dtu_config_get();
    if (!config || config->device_info.model != DTU_MODEL_4G_ETHERNET) {
        return NULL;
    }

    DTU_LOG_INFO("4G reconnect thread started");

    while (g_network_manager.running) {
        sleep(30); /* 每30秒检查一次 */

        network_interface_t* lte_interface = &g_network_manager.interfaces[NETWORK_TYPE_4G];

        /* 检查4G连接状态 */
        if (lte_interface->status == NETWORK_STATUS_CONNECTED) {
            /* 检查ppp0接口是否还存在 */
            FILE* fp = popen("ifconfig ppp0 2>/dev/null | grep 'inet '", "r");
            if (fp) {
                char line[128];
                bool ppp_active = (fgets(line, sizeof(line), fp) != NULL);
                pclose(fp);

                if (!ppp_active) {
                    DTU_LOG_WARN("4G connection lost, attempting reconnection...");
                    lte_interface->status = NETWORK_STATUS_DISCONNECTED;

                    /* 尝试重新连接 */
                    if (configure_lte_interface(&config->ethernet_config, &config->lte_config) == DTU_OK) {
                        DTU_LOG_INFO("4G reconnection successful");
                    } else {
                        DTU_LOG_ERROR("4G reconnection failed, will retry in 30 seconds");
                        lte_interface->status = NETWORK_STATUS_ERROR;
                    }
                }
            }
        } else if (lte_interface->status == NETWORK_STATUS_ERROR ||
                   lte_interface->status == NETWORK_STATUS_DISCONNECTED) {
            /* 如果4G处于错误或断开状态，尝试重新连接 */
            DTU_LOG_INFO("Attempting to reconnect 4G...");
            if (configure_lte_interface(&config->ethernet_config, &config->lte_config) == DTU_OK) {
                DTU_LOG_INFO("4G reconnection successful");
            } else {
                DTU_LOG_ERROR("4G reconnection failed, will retry in 30 seconds");
            }
        }
    }

    DTU_LOG_INFO("4G reconnect thread stopped");
    return NULL;
}
